<?php
namespace app\controller\aiAvatar;

use app\BaseController;
use app\service\TopviewApiService;
use app\service\AvatarResourceService;
use think\facade\Db;

class Resource extends BaseController
{
    protected $apiService;
    protected $avatarResourceService;

    public function __construct(TopviewApiService $apiService)
    {
        $this->apiService = $apiService;
        $this->avatarResourceService = new AvatarResourceService();
    }

    /**
     * 获取AiAvatar列表
     */
    public function aiavatarList()
    {
        try {
            $pageNo = input('pageNo/d', 1);
            $pageSize = input('pageSize/d', 20);
            $gender = input('gender', '');
            $ethnicityIdList = input('ethnicityIdList/a', []);
            $sortField = input('sortField', 'sort');
            $sortType = input('sortType', 'desc');
            $isCustom = input('isCustom/b', false);

            // 验证sortField参数
            if (!in_array($sortField, ['sort', 'shelvingTime'])) {
                return json([
                    'code' => 400, 
                    'msg' => 'sortField参数只能是sort或shelvingTime',
                    'data' => null
                ]);
            }

            // 验证sortType参数
            if (!in_array($sortType, ['asc', 'desc'])) {
                return json([
                    'code' => 400, 
                    'msg' => 'sortType参数只能是asc或desc',
                    'data' => null
                ]);
            }

            // 验证gender参数
            if (!empty($gender) && !in_array($gender, ['male', 'female'])) {
                return json([
                    'code' => 400, 
                    'msg' => 'gender参数只能是male或female',
                    'data' => null
                ]);
            }

            $data = $this->apiService->getAiAvatarList($pageNo, $pageSize, $gender, $ethnicityIdList, $sortField, $sortType, $isCustom);
            
            // 处理URL替换为OSS URL
            $data = $this->avatarResourceService->processAvatarList($data);
            
            return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => null]);
        }
    }

    /**
     * 获取Voice列表
     */
    public function voiceList()
    {
        try {
            $pageNo = input('pageNo/d', 1);
            $pageSize = input('pageSize/d', 20);
            $language = input('language', 'en');
            $gender = input('gender', '');
            $age = input('age', '');
            $style = input('style', '');
            
            $data = $this->apiService->getVoiceList($pageNo, $pageSize, $language, $gender, $age, $style);
            
            // 替换音频地址为OSS地址
            if (isset($data['data']) && is_array($data['data'])) {
                $data['data'] = $this->replaceWithOssVoiceUrls($data['data']);
            }
            
            return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 将原始音频地址替换为OSS地址
     */
    private function replaceWithOssVoiceUrls($voices)
    {
        if (empty($voices)) {
            return $voices;
        }
        
        // 收集所有的voiceId
        $voiceIds = array_column($voices, 'voiceId');
        
        if (empty($voiceIds)) {
            return $voices;
        }
        
        // 批量查询OSS地址（只获取迁移成功的）
        $ossUrls = Db::table('voice_resources')
            ->whereIn('voice_id', $voiceIds)
            ->where('status', 1) // 只获取迁移成功的
            ->where('oss_demo_url', '<>', '') // OSS地址不为空
            ->column('oss_demo_url', 'voice_id');
        
        // 替换音频地址（只替换迁移成功的）
        foreach ($voices as &$voice) {
            $voiceId = $voice['voiceId'] ?? '';
            if ($voiceId && isset($ossUrls[$voiceId]) && !empty($ossUrls[$voiceId])) {
                // 确保OSS地址不是原始CloudFront地址
                if (strpos($ossUrls[$voiceId], 'aliyuncs.com') !== false) {
                    $voice['demoAudioUrl'] = $ossUrls[$voiceId];
                }
            }
            // 如果没有找到OSS地址或迁移失败，保持原始地址不变
        }
        
        return $voices;
    }

    /**
     * 获取上传凭证
     */
    public function getUploadCredential()
    {
        try {
            $format = input('format', 'mp4');
            $data = $this->apiService->getUploadCredential($format);
            return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取音频列表
     */
    public function audioList()
    {
        try {
            $pageNo = input('pageNo/d', 1);
            $pageSize = input('pageSize/d', 10);
            $data = $this->apiService->getAudioList($pageNo, $pageSize);
            return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage()]);
        }
    }
} 